package camid.infrastructure;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import camid.distribution.broker.Invoker;



public class ServerRequestHandler implements Runnable {
	private ServerSocket server = null;
	
	private ExecutorService executor = Executors.newCachedThreadPool();
	
	private AtomicInteger buffer = new AtomicInteger(1);
	
	private int port;
	
	public static final int DEFAULT_PORT = 15001;
	
	private Invoker invoker;
	
	private static final Logger logger = LogManager.getLogger(ServerRequestHandler.class.getName());
	
//	private AtomicInteger 
	
	public ServerRequestHandler(int port, Invoker invoker)
	{
		this.port = port;
		this.invoker = invoker;
		this.executor = Executors.newCachedThreadPool();
	}
	
	public void start()
	{
		Thread t = new Thread(this);
		t.start();
	}
	
	public void run()
	{
		try
		{
			server = new ServerSocket(port);
			logger.info("Server started and listening on " + this.port);
			
			while(buffer.get() != 0)
			{
				try 
				{
					Socket sock = this.server.accept();
					executor.submit(new Acceptor(
						invoker,
						sock));
				} 
				catch (IOException e) 
				{
					e.printStackTrace();
				}
			}
			
		} 
		catch (UnknownHostException e1) 
		{
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		finally
		{
			try {
				this.server.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void shutdown()
	{
		this.buffer.set(0);
		this.executor.shutdown();
	}
	
}
